package yjj;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
//@WebFilter(urlPatterns = "/yjj/*")
public class CoreFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //初始化函数
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        // 执行拦截的逻辑代码
        // 将req强制类型转换为HttpServletRequest对象
        HttpServletRequest request = (HttpServletRequest) req;
        // 将resp强制类型转换为HttpServletResponse对象
        HttpServletResponse response = (HttpServletResponse) resp;
        String uri = request.getRequestURI();
        if ("/yjj/login.jsp".equals(uri) || uri.endsWith(".css")){
            // 此时拦截时登录页，允许通过
            chain.doFilter(req,resp);
            return;
        }
        //获取session
        HttpSession session = request.getSession();
        Object uid = session.getAttribute("UID");
        if (uid == null){
            // 说明没有登录
            response.sendRedirect("/yjj/login.jsp");
            return;
        }
        //说明用户已经登录过，允许通过
        chain.doFilter(req,resp);
    }

    @Override
    public void destroy() {
        // 当过了过滤器销毁的时候执行
    }
}
